#! python3
# 利用 selenium 登录邮箱并发送邮件


from selenium import webdriver
from selenium.webdriver.common.keys import Keys


def gotMailBrowser(url):
    browser = webdriver.Ie()
    browser.get(url)
    return browser


def loginMail(browser, name, pwd):
    """
    登陆邮箱
    """
    linkElem = browser.find_element_by_link_text('帐号密码登录')
    linkElem.click()

    elementU = browser.find_element_by_id('u')  # 用户名输入框
    elementP = browser.find_element_by_id('p')  # 密码输入框
    elementU.clear()
    elementP.clear()
    elementU.send_keys(name)
    elementP.send_keys(pwd)

    elementBtn = browser.find_element_by_id('login_button')  # 登陆按钮
    elementBtn.click()


def writeMsg(browser, receiver, subject, content):
    # 打开写信表单
    linkElem = browser.find_element_by_link_text('写信')
    linkElem.click()

    # 收件人
    elementReceiver = browser.switch_to.active_element
    elementReceiver.send_keys(receiver)
    elementReceiver.send_keys(Keys.TAB)

    # 邮件主题
    elementSubject = browser.switch_to.active_element
    elementSubject.send_keys(subject)
    elementSubject.send_keys(Keys.TAB)

    # 邮件内容
    elementContent = browser.switch_to.active_element
    elementContent.send_keys(content)
    elementContent.send_keys(Keys.PAGE_DOWN)
    elementContent.send_keys(Keys.TAB)

    # 发送按钮
    elementBtn = browser.switch_to.active_element
    elementBtn.send_keys(Keys.ENTER)


if __name__ == '__main__':
    url = "https://xui.ptlogin2.qq.com/cgi-bin/xlogin?target=self&appid=522005705&daid=4&s_url=https://mail.qq.com/cgi-bin/readtemplate?check=false%26t=loginpage_new_jump%26vt=passport%26vm=wpt%26ft=loginpage%26target=&style=25&low_login=1&proxy_url=https://mail.qq.com/proxy.html&need_qr=0&hide_border=1&border_radius=0&self_regurl=http://zc.qq.com/chs/index.html?type=1&app_id=11005?t=regist&pt_feedback_link=http://support.qq.com/discuss/350_1.shtml&css=https://res.mail.qq.com/zh_CN/htmledition/style/ptlogin_input_for_xmail440503.css"
    name = '814375791@qq.com'
    pwd = '邮箱密码'

    browser = gotMailBrowser(url)
    loginMail(browser, name, pwd)
    writeMsg(browser, 'daiq814375791@126.com', '测试subject', '这是一封测试邮件test')
